function payTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "微信支付";
    else if (value == 2)
        return "支付宝支付";
    else if (value == 3)
        return "百度支付";
    else return ""
}

function appTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "微信公众号";
    else if (value == 2)
        return "微信小程序";
    else if (value == 3)
        return "微信授权APP";
    else if (value == 4)
        return "支付宝小程序";
    else if (value == 5)
        return "百度小程序";
    else if (value == 6)
        return "头条小程序";
    else if (value == 7)
        return "新浪微博";
    else return ""
}

function versionFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "基础版";
    else if (value == 2)
        return "专业版";
    else if (value == 3)
        return "行业版";
    else if (value == 4)
        return "平台版";
    else if (value == 5)
        return "3DVR版";
    else if (value == 6)
        return "旗舰版";
    else if (value == 7)
        return "大众名片版";
    else if (value == 8)
        return "商家名片版";
    else return ""
}

$("#mfile").fileinput({
    showPreview: true,
    showUpload: true,
    uploadLabel: "上传",removeLabel: "移除",language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=MerchantApp&f=xiangqing',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data);
})

$("#mfilegzhimg").fileinput({
    showPreview: true,
    showUpload: true,
    maxFileCount: 1,
    uploadLabel: "上传",removeLabel: "移除",language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=MerchantApp&f=gzhimg',
    allowedFileExtensions: ["jpg", "jpeg", "png"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidgzhimg").val(data.response.data);
})

$("#mfilekefuimg").fileinput({
    showPreview: true,
    showUpload: true,
    maxFileCount: 1,
    uploadLabel: "上传",removeLabel: "移除",language: "zh",
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=MerchantApp&f=kefuimg',
    allowedFileExtensions: ["jpg", "jpeg", "png"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidkefuimg").val(data.response.data);
})

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/merchantapp/list'});
        },
        dataType: "json"
    });
}

function getToken(id) {
    $.ajax({
        type: 'GET',
        url: "initmkey",
        data: {mpid: id},
        success: function (e) {
            swal({title: "操作成功", text: e.info, type: "success"})
        },
        dataType: "json"
    });
}

function cloneapp(id) {
    $("#hidmpid").val(id);
    console.log($("#hidmpid").val())
    $("#hidmpid").val(id);
    $("#cloneapp-form").modal("show");
}

function clone() {
    $.ajax({
        type: 'POST',
        url: "cloneapp",
        data: {
            mpid:$("#hidmpid").val(),
            targetmpid:$("#targetmpid").val()
        },
        success: function (data) {
            swal({title: "修改成功", text: "", type: "success"})
            $("#cloneapp-form").modal("hide");
            window.location.reload();
        },
        dataType: "json"
    });
}

function deleteOne(id) {
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/merchantapp/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function initmpwd(id) {
    swal({
        title: "更改应用账户密码",
        text: "",
        type: "info",
        input: "text",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        animation: "slide-from-top",
        inputPlaceholder: "输入该应用后台账号密码"
    }).then(function (res) {
        if (res.length == 0) {
            swal("系统将随机生成密码");
        }
        console.log("======res=" + res)
        $.ajax({
            type: 'POST',
            url: "initmpwd",
            data: {
                id: id,
                pwd: res,
            },
            success: function (e) {
                if (e.code == 0) {
                    swal({title: "操作成功", text: e.info, type: "success"})
                } else {
                    swal({title: "初始化密码失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });
    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function setadmin(id) {
    swal({
        title: "设置管理员",
        text: "",
        type: "info",
        input: "text",
        showCancelButton: true,
        closeOnConfirm: false,
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        animation: "slide-from-top",
        inputPlaceholder: "输入管理员绑定的手机号"
    }).then(function (res) {
        var re = /^[1-9]+[0-9]*]*$/;
        // if(!re.test(inputValue)){
        if (res.length == 0) {
            swal("请输入管理员手机号");
            return;
        }
        if(!(/^1[3-9][0-9]\d{8}$/.test(res))){
            swal("请输入正确的手机号");
            return false;
        }

        console.log("======res=" + res)
        $.ajax({
            type: 'POST',
            url: "setadmin",
            data: {
                id: id,
                phone: res,
            },
            success: function (e) {
                if (e.code == 0) {
                    swal({title: "操作成功", text: e.info, type: "success"})
                } else {
                    swal({title: "设置管理员失败", text: e.msg||"操作失败", type: "error"})
                }
            },
            dataType: "json"
        });
    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function setpayfile(id) {
    $("#hidmpid2").val(id);
    console.log($("#hidmpid2").val())

    $("#payfile-form").modal("show");
}

function checkPayfile(token) {
    if($("#payfile").val()==""){
        swal({title: "提示", text: "支付密钥文件", type: "error"})
        return false;
    }
    return true;
}

function viewtoken(token) {

    swal({title: "应用TOKEN", text: token, type: "success"})
}

function clearredis(id) {

    $.ajax({
        type: 'POST',
        url: "clearredis",
        data: {
            id: id,
        },
        success: function (status) {
            if (status == 1) {
                swal({title: "操作成功", text: "", type: "success"})
                $('#mytable').bootstrapTable('refresh', {url: '/admin/merchantapp/list'});
            } else {
                swal({title: "操作失败", text: "", type: "error"})
            }
        },
        dataType: "json"
    });
}

function actlFormatter(value, row, index) {
    var state = row.state;
    var appType = row.appType;
    var id = row.id;
    var token = row.token;
    var res = '<button typ-e="button" class="btn-sm btn-info" onclick="getToken(\'' + id + '\')" >获取MKEY</button>';
    res += ' <button typ-e="button" class="btn-sm btn-info" onclick="initmpwd(\'' + id + '\')" >重置商户应用账户密码</button>';
    res += ' <button typ-e="button" class="btn-sm btn-info" onclick="viewtoken(\'' + token + '\')" >查看TOKEN</button>';
    res += ' <button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';

    if ($("#isAdmin").val() == 1) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">清除缓存</button>';
    if ($("#isAdmin").val() == 1) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="cloneapp(\'' + id + '\')">一键克隆</button>';
    if ($("#isAdmin").val() == 1) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="setadmin(\'' + id + '\')">设置管理员</button>';
    if ($("#isAdmin").val() == 1) res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="setpayfile(\'' + id + '\')">设置支付密钥</button>';

    return res;
}

var editsw = [];
/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    console.log("========start to modify action...")
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#name').val(data.name)
    modal.find('#sid').val(data.sid)
    modal.find('#mchid').val(data.mchid)
    modal.find('#kefu1').val(data.kefu1)
    modal.find('#kefu2').val(data.kefu2)
    modal.find('#appType').find("option[value='" + data['appType'] + "']").attr("selected", true);
    modal.find('#payType').find("option[value='" + data['payType'] + "']").attr("selected", true);
    modal.find('#version').find("option[value='" + data['version'] + "']").attr("selected", true);

    modal.find('#appid').val(data.appid)
    modal.find('#appsecret').val(data.appsecret)
    modal.find('#paykey').val(data.paykey)

    $("#mfile2").fileinput('destroy');
    $("#mfile2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",
        language: "zh",
        maxFileCount: 1,
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.pic),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.pic, 'MerchantApp', "pic", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=MerchantApp&f=pic',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidpic2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidpic2").val('');
    })
    $("#hidpic2").val(data.pic)

    $("#mfilegzhimg2").fileinput('destroy');
    $("#mfilegzhimg2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",
        language: "zh",
        maxFileCount: 1,
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.gzhimg),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.gzhimg, 'MerchantApp', "gzhimg", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=MerchantApp&f=gzhimg',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidgzhimg2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidgzhimg2").val('');
    })
    $("#hidgzhimg2").val(data.gzhimg)


    $("#mfilekefuimg2").fileinput('destroy');
    $("#mfilekefuimg2").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",removeLabel: "移除",
        language: "zh",
        maxFileCount: 1,
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.kefuimg),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.kefuimg, 'MerchantApp', "kefuimg", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=MerchantApp&f=kefuimg',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidgzhimg2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidgzhimg2").val('');
    })
    $("#hidkefuimg2").val(data.kefuimg)

    if ($("#isAdmin").val() == 1){
        // $("#payfile").fileinput({
        //     showUpload: true,
        //     uploadLabel: "上传",
        //     removeLabel: "移除",
        //     language: "zh",
        //     elErrorContainer: '#kartik-file-errors',
        //     uploadUrl: '/admin/merchantapp/uploadPayfile?tid='+data.id
        // }).on("fileuploaded", function (event, data) {
        //     console.log('--------------------fileuploaded');
        //     console.log(data);
        //     $("#payfile-form").modal("hide");
        // })
    }
})

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

$(function () {

    var sw = [];
    $("#modal-add-form .js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })

    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })

    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/merchantapp/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 20,//单页记录数
        pageList: [20, 50, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '应用名',
                field: 'name'
            },
            {
                title: '商家分店ID',
                field: 'sid',
                visible: false
            },
            {
                title: '分店支付商户ID',
                field: 'mchid'
            },
            {
                title: '支付类型',
                field: 'payType',
                formatter: "payTypeFormatter"
            },
            {
                title: '支付渠道',
                field: 'appType',
                formatter: "appTypeFormatter"
            },
            {
                title: '应用版本',
                field: 'version',
                formatter: "versionFormatter"
            },
            {
                title: '应用logo',
                field: 'pic',
                formatter: "imgFormatter"
            },
            {
                title: '应用id',
                field: 'appid'
            },
            {
                title: '启用状态',
                field: 'state',
                formatter: "stateFormatter"
            },
            // {
            //     title: '是否总店',
            //     field: 'isMaster',
            //     formatter: "sfFormatter"
            // },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 300,
                formatter: actlFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        console.log(params)
        return params;
    }

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    if ($("#hidpic").attr("required") == "required"
        && $("#hidpic").val() == "") {
        swal({title: "请上传图片", text: "", type: "warning"})
        return false;
    }
    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    // if ($("#hidpic2").attr("required") == "required"
    //     && $("#hidpic2").val() == "") {
    //     swal({title: "请上传图片", text: "", type: "warning"})
    //     return false;
    // }
    return true;
}